package com.javaziliao.design.bridge.function;

import cn.hutool.core.convert.Convert;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.javaziliao.design.bridge.abst.factory.RegisterLoginComponentFactory;
import com.javaziliao.design.pojo.UserInfo;
import com.javaziliao.design.repo.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@Component
public class RegisterLoginByGitee extends AbstractRegisterLoginFunc implements IRegisterLoginFunc {
    @Value("${gitee.state}")
    private String giteeState;
    @Value("${gitee.token.url}")
    private String giteeTokenUrl;
    @Value("${gitee.user.url}")
    private String giteeUserUrl;
    @Value("${gitee.user.prefix}")
    private String giteeUserPrefix;

    @Autowired
    private UserRepository userRepository;

    @PostConstruct
    private void initFuncMap() {
        RegisterLoginComponentFactory.funcMap.put("GITEE", this);
    }

    @Override
    public String login3rd(HttpServletRequest request) {
        String code = request.getParameter("code");
        // 授权码换取token
        String result = HttpUtil.post(giteeTokenUrl.concat(code), "");
        try {
            System.out.println(result);
            JSONObject jsonObject = JSON.parseObject(result);
            String accessToken = Convert.toStr(jsonObject.get("access_token"));
            String userResult = HttpUtil.get(giteeUserUrl.concat(accessToken));
            JSONObject userObject = JSON.parseObject(userResult);
            String userName = giteeUserPrefix.concat(Convert.toStr(userObject.get("login")));
            String password = userName;
            return autoRegister3rdAndLogin(userName, password);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String autoRegister3rdAndLogin(String userName, String password) {
        if (super.commonCheckUserExists(userName, userRepository)) {
            return super.login(userName, password);
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUserName(userName);
        userInfo.setUserPassword(password);
        userInfo.setCreateDate(new Date());
        super.commonRegister(userInfo, userRepository);
        return super.commonLogin(userName, password, userRepository);
    }
}
